#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using CchenSoft.Workflow.Spi;
using System.Collections;
using System.Collections.Generic;
using System;

namespace CchenSoft.Workflow.Util
{
    /**
     * Sets the transient variable "mostRecentOwner" to the owner of the most
     * recent step that had an id equal to one of the values in the stepId list. If there is
     * none found, the variable is unset. This function accepts the following
     * arguments:
     *
     * <ul>
     *  <li>stepId - a comma-seperated list of the most recent steps to look for (required)</li>
     * </ul>
     */
    public class MostRecentOwner : IFunctionProvider
    {
        //~ Methods ////////////////////////////////////////////////////////////////

        public void Execute(IDictionary transientVars, IDictionary args)
        {
            // expects a stepId name/value pair
            string stepIdString = (string)args["stepId"];
            IWorkflowEntry entry = (IWorkflowEntry)transientVars["entry"];

            if (stepIdString == null)
            {
                throw new WorkflowException("This function expects a stepId!");
            }

            string[] st = stepIdString.Split(',');
            List<int> stepIds = new List<int>();

            for (int i = 0; i < st.Length; i++)
            {
                stepIds.Add(Convert.ToInt32(st[i].Trim()));
            }

            IWorkflowStore store = (IWorkflowStore)transientVars["store"];
            IList<IStep> historySteps = store.FindHistorySteps(entry.Id);

            foreach (IStep step in historySteps)
            {
                if (stepIds.Contains(step.StepId) && !string.IsNullOrEmpty(step.Owner))
                {
                    transientVars["mostRecentOwner"] = step.Owner;

                    break;
                }
            }
        }
    }
}
